from writer import Writer
import sys

class LatexWriter(Writer):
	def __init__(self):
		self.__bold = False
		self.__italic = False
		self.__inlineCode = False
		self.__outputStr = ''

	def finalise(self):
		sys.stdout.write(self.__outputStr)

	def header(self, level, text):
		# Since latex doesnt have deeper header levels than 3, I'm
		# wrapping around. Let's hope this works out for everyone...
		# (probably not)
		if level > 3:
			level = level % 3

		s = ''
		if level == 1:
			s = 'section'
		elif level == 2:
			s = 'subsection'
		elif level == 3:
			s = 'subsubsection'
		
		self.outputNL('')
		self.outputNL('\\'+ s + '{' + text +'}')

	def outputNL(self, str):
		""" Puts str in the outputbuffer and
		ends the current line
		"""
		self.__outputStr += str + '\n'
	
	def output(self, str):
		self.__outputStr += str

	def decreaseQuoteLevel(self):
		self.outputNL('')
		self.outputNL("\\begin{quote}")

	def increaseQuoteLevel(self):
		self.outputNL('')
		self.outputNL("\\end{quote}")
		# Start each blockquote with a paragraph
		self.paragraph()

	def toggleBold(self):
		# Real bold in latex isn't advisable, so just another emph
		# tag. Yeah, bold isn't bold... 
		if self.__bold:
			self.output("}")
			self.__bold = False
		else:
			self.output("{\\emph")
			self.__bold = True

	def toggleInlineCode(self):
		# TODO: Check if the delimiting character is used in the code
		# and if so, pick another one
		if self.__inlineCode:
			self.output('$')
			self.__inlineCode = False
		else:
			self.output('\\verb$')
			self.__inlineCode = True

	def toggleItalic(self):
		if self.__italic:
			self.output("}")
			self.__italic = False
		else:
			self.output("{\\emph")
			self.__italic = True

	def character(self, char):
		self.output(self.escapeLatex(char))

	def newline(self):
		self.outputNL('')
		self.outputNL(" \\\\")

	def paragraph(self):
		self.outputNL('')
		self.outputNL('')

	def startcode(self):
		self.outputNL('')
		self.outputNL("\\begin{verbatim}")

	def stopcode(self):
		self.outputNL("\\end{verbatim}")
	
	def line(self, line):
		self.outputNL(self.escapeLatex(line))

	def link(self, text, url):
		pass
		
	def printLink(self, text, loc):
		pass

	def refLink(self, text, ref):
		pass

	def linkLabel(self, id, url):
		pass

	def equationchar(self, char):
		self.output(char)

	def beginequation(self):
		self.output('$')

	def endequation(self):
		self.output('$')

	def escapeLatex(self,input):
		return input.replace('{', '\\{').replace('}', '\\}').replace('<', '$<$').replace('>', '$>$')

